<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/15
 * Time: 15:05
 */

namespace App\Http\Controllers\Api\Doctor;

use App\Http\Controllers\ApiController;
use App\LogicService\Contracts\UserGroupLogicContract;
use App\LogicService\Contracts\UserGroupMemberLogicContract;
use App\Transformers\UserGroupTransformer;
use Illuminate\Http\Request;
use RongCloud;

class UserGroupController extends ApiController
{


    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    protected $userGroup;

    protected $userGroupMember;

    protected $rong;

    /**
     * UserGroupController constructor.
     * @param Request $request
     * @param UserGroupLogicContract $userGroup
     * @param UserGroupMemberLogicContract $userGroupMember
     */

    public function __construct(Request $request, UserGroupLogicContract $userGroup,
                                UserGroupMemberLogicContract $userGroupMember)
    {
        parent::__construct();

        $this->request = $request;
        $this->rong = new RongCloud(config('app.rongcloud_appKey'), config('app.rongcloud_appSecret'));
        $this->userGroup = $userGroup;
        $this->userGroupMember = $userGroupMember;
    }


    public function store()
    {
        $this->validate($this->request, [
            'name' => 'required|string',
            'notice' => 'string',
            'accounts' => 'required|array',
        ]);
        $user = \Auth::user();

        $name = $this->request->input('name');
        $notice = $this->request->input('notice');
        $data = [
            'account' => $user->account,
            'name' => $name,
            'notice' => $notice
        ];
        $group = $this->userGroup->store($data);

        if ($group) {
            //保存群成员到数据库
            $accounts = $this->request->input('accounts');
            $this->userGroupMember->addUserlist($group->id, $accounts);
            //生成融云群组
            $this->rong->group()->create($accounts, $group->id, $name);

            //推送用户
            $push_arr = [
                "platform" => ["ios", "android"],
                "audience" => ["userid" => [$accounts]],
                "notification" => ["alert" => '医生:' . $user->name . '添加您加入群' . $name]
            ];

            $this->rong->push()->broadcastPush(json_encode($push_arr));

        }

        return $this->response(['group' => $group]);
    }


    public function delete()
    {

        $this->validate($this->request, [
            'group_id' => 'required|integer',
        ]);

        $user = \Auth::user();
        if ($user->type == 1) {
            $rong_account = 'patient_' . $user->account;
        } else {
            $rong_account = 'doctor_' . $user->account;
        };
        //判断群组是否存在
        $group_id = $this->request->input('group_id');
        $result = $this->userGroup->isGroup($user->account, $group_id);
        if ($result) {
            $result = $this->userGroup->delete($group_id);
            if ($result) {
                $this->userGroupMember->deleteUserList($group_id);
                //解散融云群组

                $this->rong->group()->dismiss($rong_account, $group_id);
            }
        }
        return $this->response(['result' => $result]);
    }

    /**
     * 获取用户群组
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList()
    {

        $user = \Auth::user();

        if ($user->type == 1) {
            $rong_account = 'patient_' . $user->account;
        } else {
            $rong_account = 'doctor_' . $user->account;
        };
        $data = $this->userGroup->getList($rong_account);

        return $this->collection($data, new UserGroupTransformer());
    }


    public function update()
    {
        $this->validate($this->request, [
            'name' => 'string',
            'notice' => 'string',
            'group_id' => 'required|integer',
        ]);

        $user = \Auth::user();
        $name = $this->request->input('name');
        $notice = $this->request->input('notice');
        $group_id = $this->request->input('group_id');

        //判断用户是否是群主
        $result = $this->userGroup->isGroup($user->account, $group_id);

        if ($result) {
            $up_data = [];
            if (!empty($name)) {
                $up_data['name'] = $name;
                $this->rong->group()->refresh($group_id, $name);
                $content = array(
                    "operatorUserId"=>'doctor_'.$user->account,
                    "operation"=>"Rename",
                    "data"=>array(
                        "operatorNickname"=>$user->name,
                        "targetGroupName"=>$name),
                    "message"=>"修改本群名为".$name,
                    "extra"=>""
                );
                $this->rong->message()
                    ->publishGroup('doctor_'.$user->account, $group_id, 'RC:GrpNtf',json_encode($content), 'thisisapush', '{\"pushData\":\"修改本群名\"}', '1', '1', '0');


            }
            if (!empty($notice)) {
                $up_data['notice'] = $notice;
            }

            if (empty($notice) && empty($name)) {
                return $this->setMessage('请填写你要修改的内容')->setCode('400004')->response();
            }
            $result = $this->userGroup->update($group_id, $up_data);
        }
        return $this->response(['result' => $result]);
    }


    public function show()
    {
        $this->validate($this->request, [
            'group_id' => 'required|integer',
        ]);

        $user = \Auth::user();

        $group_id = $this->request->input('group_id');

        //返回群组信息
        $result = $this->userGroup->show($group_id);

        return $this->item($result, new UserGroupTransformer());
    }


    /**
     * 返回群组二维码
     * @return string
     */
    public function createInsertQrCode()
    {
        $this->validate($this->request, [
            'group_id' => 'required|integer',

        ]);


        $url = $this->request->server('HTTP_HOST');

        $group_id = $this->request->input('group_id');

        $api_token = $this->request->input('api_token');


        $qrCode_url = $url . '/api/group/member/store?api_token=' . $api_token . '&group_id=' . $group_id;

        $path = "qrcodes\group_$group_id.png";

        \QrCode::format('png')->size(100)->generate($qrCode_url, public_path($path));

        return $path;

    }


}